<template>
  <div class="book-detail">
    <div class="book-info">
      <dl>
        <dt>
          <img :src="bookInfo.coverUrl" v-default-img="defaultImg" />
        </dt>
        <dd>
          <h3 class="bookTitle" v-text="bookInfo.bookTitle"></h3>
          <p class="ellipsis authorName" v-text="bookInfo.authorName"></p>
          <p class="bookTxt">
            <span
              v-if="bookInfo.category"
              v-text="bookInfo.category.name"
            ></span>
            <span>{{ bookInfo.writingProcess | writingProcess }}</span>
            <span v-text="bookInfo.wordCount + ' Words'"></span>
          </p>
          <div
            class="bookIntro"
            v-if="bookInfo.bookIntro && bookInfo.bookIntro.length > 0"
          >
            <p :class="{ isEllipsis }">
              {{ bookInfo.bookIntro }}
            </p>
            <li
              class="introduce-btn"
              v-if="isUnfoldOrFoldBtn"
              @click="isEllipsis = !isEllipsis"
            >
              <template v-if="isEllipsis">
                <svg-icon icon-class="unfold"></svg-icon>
                Unfold
              </template>
              <template v-else>
                <svg-icon icon-class="fold"></svg-icon>
                Fold
              </template>
            </li>
          </div>
          <div class="bookIntro-btn-box">
            <button
              class="bookIntro-btn"
              :class="{ disBtn: isBookSelf }"
              @click="bookToBookCase"
              v-text="isBookSelf ? 'Added' : 'Add To Bookself'"
            ></button>
            <button class="bookIntro-btn" @click="toReader(1)">Read</button>
          </div>
        </dd>
      </dl>
    </div>
    <main>
      <h2>The book</h2>
      <article>
        <h6
          class="chapterName"
          @click="toReader(1)"
          v-text="bookInfo.firstChapterName"
        ></h6>
        <p class="chapterContent" v-html="bookInfo.firstChapterContent"></p>
        <button class="bookIntro-btn" @click="toReader(2)">Read On</button>
      </article>
      <h2>Related recommendati</h2>
      <ul class="recommend-list">
        <Cover
          v-for="item of recommendList"
          :key="item.contentId"
          :item="item"
        />
      </ul>
    </main>
  </div>
</template>

<script>
import { mapMutations, mapGetters } from "vuex";
import axios from "api/index";
import api from "api/global_variable";
import Cover from "components/common/Cover/Index";
export default {
  data() {
    return {
      defaultImg: require("@/assets/images/default-cover.png"),
      bookId: this.$route.params.id, //书籍ID
      bookInfo: {}, //书籍信息
      isEllipsis: true, // 是否三行展示
      isUnfoldOrFoldBtn: false, // 是否显示展开/隐藏按钮
      recommendList: [], //推荐书籍列表
      isBookSelf: 0, // 是否加入书架
    };
  },
  // 设置meta信息---- 用于fb与Twitter分享
  // metaInfo() {
  //   return {
  //     // title: this.setting.title,
  //     meta: [
  //       // fb--og分享
  //       { property: "og:title", content: this.bookInfo.bookTitle },
  //       { property: "og:url", content: window.location.href },
  //       { property: "og:image", content: this.bookInfo.coverUrl },
  //       { property: "og:image:width", content: "1200" },
  //       { property: "og:image:height", content: "628" },
  //       { property: "og:description", content: this.bookInfo.bookIntro },
  //       { property: "og:type", content: "article" },
  //       { property: "article:author", content: this.bookInfo.authorName },
  //       { property: "article:published_time", content: this.bookInfo.editTime },
  //       // twitter 分享
  //       { name: "twitter:card", content: "summary_large_image" },
  //       { name: "twitter:creator", content: "FishNovel" },
  //       { name: "twitter:title", content: this.bookInfo.bookTitle },
  //       { name: "twitter:description", content: this.bookInfo.bookIntro },
  //       { name: "twitter:image", content: this.bookInfo.coverUrl },
  //       // { name: "twitter:domain", content: window.location.href },
  //     ],
  //   };
  // },
  filters: {
    // 过滤写作进程
    writingProcess(code) {
      let list = {
        0: "Serial",
        1: "End",
        2: "New",
      };
      return list[code];
    },
  },
  components: {
    Cover,
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  watch: {},
  created() {},
  mounted() {
    this.getinfo();
    this.getBookRead();
  },
  methods: {
    ...mapMutations({
      // setShowPopup: "SET_SHOW_POPUP",
      setCurrentDialog: "SET_CURRENT_DIALOG",
    }),
    async getinfo() {
      try {
        const baseUrl = api.apiUrl;
        let url = baseUrl + `/book/info/${this.bookId}`;
        let res = await axios.get(url);
        if (res.code === 1) {
          this.bookInfo = res.source;
          this.bookInfo.firstChapterContent =
            this.bookInfo.firstChapterContent.replace(/\n/g, "\n\n");
          if (this.bookInfo.bookIntro.length > 200) {
            this.isUnfoldOrFoldBtn = true;
          } else {
            this.isEllipsis = false;
          }
          this.recommend(this.bookId, res.source.categoryId1);
          this.sendLog(res.source);
        }
      } catch (e) {
        console.log(e);
      }
    },
    // 发送日志
    async sendLog(val) {
      let opts = {
        logType: 1, //日志类型：1.电子书，2.AI听书，3.有声小说
        isTitlePage: 1, //是否扉页：1.是，0.否
        bookId: this.bookId, //书籍id
        bookName: val.bookTitle, //书籍名称
        authorName: val.authorName, //作者名称
        cpId: val.channelId, //cp方id
        preference: val.site, //书籍男女：1.男，2.女
        categoryIdOne: val.categoryId1, //书籍分类一级id
        categoryIdTwo: val.categoryId2, //书籍分类二级id
        isFreeBook: val.isFree, //是否免费书籍：1.是，0.否
      };
      await this.$api.logger.book_read_analysis(opts);
    },
    // 查询的书籍列表
    async recommend(bookId, categoryId) {
      try {
        let params = {
          bookId,
          categoryId,
        };
        let res = await this.$api.book.recommend(params);
        if (res.code === 1) {
          this.recommendList = res.source;
        }
      } catch (e) {
        console.log(e);
      }
    },
    // 添加到书架
    async bookToBookCase() {
      if (this.userInfo) {
        if (this.isBookSelf) {
          let params = {
            bookIds: this.bookId, //书籍id
          };
          let res = await this.$api.reader.delBookToBookCase(params);
          if (res.code === 1) {
            this.isBookSelf = 0;
            this.$message({
              duration: "1500",
              message: "Move successful",
            });
          } else {
            this.$message({
              message: res.message ? res.message : "Fail to add",
              duration: "1500",
              type: "error",
            });
          }
        } else {
          let params = {
            bookId: this.bookId, //书籍id
          };
          let res = await this.$api.reader.addBookToBookCase(params);
          if (res.code === 1) {
            this.isBookSelf = 1;
            this.$message({
              message: "Add successful",
              duration: "1500",
              type: "success",
            });
          } else {
            this.$message({
              message: res.message ? res.message : "Fail to add",
              duration: "1500",
              type: "error",
            });
          }
        }
      } else {
        this.setCurrentDialog({ current: "login" });
        // this.setShowPopup(true);
      }
    },
    // 查询用户的书籍阅读记录
    async getBookRead() {
      let params = {
        bookId: this.bookId, //书籍id
      };
      let res = await this.$api.reader.getBookRead(params);
      if (res.code === 1 && res.source) {
        this.isBookSelf = res.source.isCollect;
      }
    },
    // 跳转阅读器
    toReader(sort) {
      if (sort >= 2) {
        let map;
        if (this.utils.seekStore("fn_readingLog")) {
          map = new Map(this.utils.getStore("fn_readingLog"));
          let maxSort = map.has(this.bookId)
            ? Math.max(map.get(this.bookId), sort)
            : sort;
          map.set(this.bookId, maxSort);
        } else {
          map = new Map();
          map.set(this.bookId, sort);
        }
        this.utils.setStore("fn_readingLog", Array.from(map.entries()));
      }
      const { href } = this.$router.resolve({
        name: "reader",
        params: { id: this.bookId }, //书籍id
      });
      window.open(href, "_blank");
    },
  },
};
</script>

<style lang="scss" scoped>
.book-detail {
  width: 1200px;
  margin: 45px auto;
  .book-info {
    width: 100%;
    min-height: 440px;
    // height: auto;
    padding-bottom: 32px;
    border-bottom: 8px solid #eeeeee;
    box-sizing: border-box;
    > dl {
      width: 100%;
      min-height: 320px;
      display: flex;
      justify-content: space-between;
      dt {
        margin-right: 46px;
        img {
          width: 240px;
          height: 320px;
          box-shadow: 0px 1px 6px 1px rgba(0, 0, 0, 0.2);
          border-radius: 16px;
        }
      }
      dd {
        width: 100%;
        display: flex;
        flex-direction: column;
        .bookTitle {
          margin-top: 35px;
          line-height: 28px;
          font-size: 20px;
          font-family: PingFangSC-Semibold, PingFang SC;
        }
        p {
          font-size: 16px;
          color: #999999;
          line-height: 22px;
          &.authorName {
            margin-top: 16px;
          }
          &.bookTxt {
            margin-top: 24px;
            span {
              &:not(:first-child)::before {
                content: "/";
                padding: 0 10px;
              }
            }
          }
        }
        .bookIntro {
          margin-top: 24px;
          white-space: pre-wrap;
          > p {
            line-height: 22px;
            position: relative;
            color: #666666;
            font-family: PingFangSC-Regular, PingFang SC;
            &.isEllipsis {
              display: -webkit-box;
              overflow: hidden;
              text-overflow: ellipsis;
              word-wrap: break-word;
              line-clamp: 3 !important;
              -webkit-line-clamp: 3 !important;
              -webkit-box-orient: vertical;
            }
          }
          .introduce-btn {
            line-height: 22px;
            font-size: 16px;
            color: #e86472;
            cursor: pointer;
            font-family: PingFangSC-Regular, PingFang SC;
            z-index: 9;
            text-align: right;
          }
        }
        .bookIntro-btn-box {
          margin-top: 24px;
          .bookIntro-btn {
            margin-right: 32px;
          }
        }
      }
    }
  }
  main {
    width: 100%;
    height: auto;
    box-sizing: border-box;
    background: #fff;
    border-radius: 16px;
    h2 {
      display: flex;
      align-items: center;
      font-size: 26px;
      line-height: 37px;
      margin-top: 80px;
      font-weight: 600;
      font-family: PingFangSC-Semibold, PingFang SC;
      &::before {
        content: "";
        width: 8px;
        height: 30px;
        border-radius: 0px 4px 4px 0px;
        display: inline-block;
        margin-right: 8px;
        background: #e86472ff;
      }
    }
    article {
      .chapterName {
        font-weight: 500;
        cursor: pointer;
        font-size: 16px;
        margin-top: 24px;
        line-height: 22px;
        font-family: PingFangSC-Medium, PingFang SC;
      }
      .chapterContent {
        font-size: 16px;
        white-space: pre-wrap;
        color: #666666;
        margin-top: 16px;
        line-height: 24px;
        font-family: PingFangSC-Regular, PingFang SC;
      }
      .bookIntro-btn {
        display: block;
        margin: 27px auto;
      }
    }
    .recommend-list {
      display: flex;
      margin-top: 53px;
      overflow-y: hidden;
      overflow-x: auto;
      // &::-webkit-scrollbar {
      //   width: 0;
      //   height: 0;
      // }
      .cover-li {
        &:not(:last-child) {
          margin-right: 96px;
        }
      }
    }
  }
  .bookIntro-btn {
    width: 148px;
    height: 38px;
    cursor: pointer;
    font-size: 16px;
    color: #fff;
    background: #e86472;
    border-width: 0;
    border-radius: 6px;
    &.disBtn {
      background: #cccccc;
    }
  }
}
</style>
